
#include <iostream>
#include <signal.h>

#include "../comm/httplib.h"
#include "Control.hpp"

using namespace httplib;
using namespace ns_control;

static Control *ctrl_ptr = nullptr;

void Recovery(int signo)
{
    // LOG(DEBUG, "收到信号了\n");
    ctrl_ptr->RecoveryMachine();
}

//  获取用户的http请求 通过Control控制器，来完成对路由功能的解耦，也就是说对于所有收到请求的处理 我们交付给control统一处理
//  而control内部组合了model和view

int main()
{
    //  用户请求服务器路由功能
    Server svr;
    Control ctrl;

    ctrl_ptr = &ctrl;
    signal(SIGQUIT, Recovery);

    //  获取所有的题目列表
    svr.Get("/all_questions", [&ctrl](const Request &req, Response &resp)
            { 
                std::string html;
                ctrl.HtmlForAllQuestions(&html);
                resp.set_content(html, "text/html;charset=utf-8"); });

    //  用户根据题目编号，获取题目内容
    svr.Get(R"(/question/(\d+))", [&ctrl](const Request &req, Response &resp)
            {
                std::string  num = req.matches[1];
                std::string html;
                ctrl.HtmlForNumQuestion(num, &html);
                resp.set_content(html, "text/html;charset=utf-8"); });

    //  用户提交代码，使用判题功能
    svr.Post(R"(/judge/(\d+))", [&ctrl](const Request &req, Response &resp)
             {
                std::string  num = req.matches[1];
                std::string result_json;
                ctrl.Judge(num, req.body, &result_json);
                resp.set_content(result_json , "application/json;charset=utf-8"); });

    svr.set_base_dir("./wwwroot");
    svr.listen("0", 8888);

    return 0;
}